package com.lingyl.gulimall.product.exception;

import com.lingyl.common.exception.BizCodeEnume;
import com.lingyl.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>Title: 集中处理所有异常</p>
 * <p>Description: 统一处理这个com.lingyl.gulimall.product.controller包下的异常</p>
 * @author Alan.lingyl
 * @version 1.0.0
 * @date 2021-02-01 15:16
 * @copyright 2020-2021.year, Alan.lingyl, All right reserved.
 */
@Slf4j
//@ResponseBody
//@ControllerAdvice(basePackages = "com.lingyl.gulimall.product.controller")
@RestControllerAdvice(basePackages = "com.lingyl.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {


    @ExceptionHandler(value= MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题{},异常类型:{}",e.getMessage(),e.getClass());
        BindingResult result = e.getBindingResult();
        Map<String,String> errMap = new HashMap<>();
        result.getFieldErrors().forEach(item -> {
            errMap.put(item.getField(),item.getDefaultMessage());
        });
        return R.error(BizCodeEnume.VALID_EXCEPTION.getCode(),BizCodeEnume.VALID_EXCEPTION.getMsg()).put("data",errMap);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable){
        log.error(throwable.getMessage());
        throwable.printStackTrace();
        return R.error(BizCodeEnume.UNKNOWN_EXCEPTION.getCode(),BizCodeEnume.UNKNOWN_EXCEPTION.getMsg());
    }

}
